import { GlobalConfig } from '@/GlobalConfig';
import ChatHub from '@/services/chatHub';
import {
  smartChemistryClear,
  smartChemistryCreate,
  smartChemistryPagination,
} from '@/services/swagger/smartChemistry';
import { userStorage } from '@/userStorage';
import { Button, Input, Layout, List, Space, notification } from 'antd';
import React, { useEffect, useRef, useState } from 'react';

const { Content } = Layout;

const Chat: React.FC = () => {
  const [messages, setMessages] = useState<{ text: string; isUser: boolean }[]>([]);
  const [inputValue, setInputValue] = useState<string>('');
  const listRef = useRef<HTMLDivElement>(null); // 创建ref

  // 创建或获取 ChatHub 实例
  const token = userStorage.getToken() as string;
  const chatHub = ChatHub.getInstance(GlobalConfig.API_URL + '/chemistry/notification', token);

  const handleSendMessage = async () => {
    if (inputValue.trim()) {
      const result = await smartChemistryCreate({ question: inputValue });
      if (result.success) {
        setMessages((prevMessages) => [...prevMessages, { text: inputValue, isUser: true }]);
        setInputValue('');
        await chatHub.SendChemistryAskMessage(inputValue);
      } else {
        notification.error({
          message: '消息发送失败',
          description: '请重试或检查网络连接。',
        });
      }
      setInputValue('');
    }
  };

  const clearMessage = async () => {
    const result = await smartChemistryClear();
    if (result.success) {
      setMessages([]);
      notification.info({
        message: '消息清理成功',
      });
    } else {
      notification.error({
        message: '消息清理失败',
        description: '请重试或检查网络连接。',
      });
    }
  };

  const getChatHistory = async () => {
    try {
      const result = await smartChemistryPagination({ PageNumber: 1, PageSize: 10 });

      if (result.success) {
        // 检查 data 是否存在并且是数组
        const newMessages = Array.isArray(result.data)
          ? result.data.reverse().flatMap((data) => [
              {
                text: data.question as string,
                isUser: true,
              },
              {
                text: data.answer as string,
                isUser: false,
              },
            ])
          : []; // 如果没有数据，则返回一个空数组

        // 更新状态，将新消息添加到现有的 messages 中
        setMessages((prevMessages) => [...prevMessages, ...newMessages]);
      } else {
        notification.error({
          message: '加载历史记录失败',
          description: '请重试或检查网络连接。',
        });
      }
    } catch (error) {
      // 处理错误情况
      notification.error({
        message: '错误',
        description: '无法获取历史聊天记录。',
      });
    }
  };

  // 订阅消息接收事件
  useEffect(() => {
    chatHub.onReceivePrivateMessage((message) => {
      setMessages((prevMessages) => [...prevMessages, { text: `${message}`, isUser: false }]);
    });
  }, [chatHub]);

  useEffect(() => {
    const fetchChatHistory = async () => {
      await getChatHistory(); // 获取历史记录
      // 滚动到底部
      if (listRef.current) {
        listRef.current.scrollTop = listRef.current.scrollHeight;
      }
    };

    fetchChatHistory();
  }, []);

  useEffect(() => {
    // 滚动到底部
    if (listRef.current) {
      listRef.current.scrollTop = listRef.current.scrollHeight;
    }
  }, []);

  return (
    <Layout style={{ height: '100vh' }}>
      <Content style={{ display: 'flex', flexDirection: 'column', padding: '10px' }}>
        <div
          ref={listRef}
          style={{
            flex: 1,
            overflowY: 'auto',
            maxHeight: 'calc(100vh - 180px)', // 限制最大高度以适应输入框
            padding: '10px',
            scrollbarWidth: 'none', // Firefox
            msOverflowStyle: 'none', // Internet Explorer and Edge
          }}
          className="scroll-container"
        >
          <List
            style={{ padding: 0 }}
            bordered={false}
            dataSource={messages}
            renderItem={(item) => (
              <List.Item style={{ border: 'none', padding: '10' }}>
                <div
                  style={{
                    display: 'flex',
                    justifyContent: item.isUser ? 'flex-end' : 'flex-start',
                    width: '100%',
                  }}
                >
                  <div
                    style={{
                      background: item.isUser ? '#1890ff' : '#f0f0f0',
                      color: item.isUser ? '#fff' : '#000',
                      borderRadius: '10px',
                      padding: '10px',
                      maxWidth: '70%',
                      wordBreak: 'break-word',
                    }}
                  >
                    <div dangerouslySetInnerHTML={{ __html: item.text }} />
                  </div>
                </div>
              </List.Item>
            )}
          />
        </div>
        <div style={{ padding: '10px', background: '#fff', position: 'sticky', bottom: 0 }}>
          <Space.Compact style={{ width: '100%' }}>
            <Input
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
              onPressEnter={handleSendMessage}
              placeholder="输入消息..."
              style={{ borderRadius: '5px 0 0 5px' }}
            />
            <Button
              type="primary"
              onClick={handleSendMessage}
              style={{ borderRadius: '0 5px 5px 0' }}
            >
              发送
            </Button>
            <Button
              type="default"
              onClick={clearMessage} // 清空消息记录
              style={{ marginLeft: '5px', borderRadius: '5px' }}
            >
              清空记录
            </Button>
          </Space.Compact>
        </div>
      </Content>
    </Layout>
  );
};

export default Chat;
